package middleware

import (
	"encoding/base64"
	"strings"

	"gitee.com/youkelike/ziam/zcode/zcode"
	"gitee.com/youkelike/ziam/zerrors"
	"gitee.com/youkelike/ziam/zutils/response"
	"github.com/gin-gonic/gin"
)

func NewBasicAuth(compare func(username, password string) bool) gin.HandlerFunc {
	return func(c *gin.Context) {
		auth := strings.SplitN(c.Request.Header.Get("Authorization"), " ", 2)
		if len(auth) != 2 || auth[0] != "Basic" {
			response.Write(c, zerrors.WithCode(zcode.ErrSignatureInvalid, "Authorization header format is wrong."), nil)
			c.Abort()
			return
		}

		payload, _ := base64.StdEncoding.DecodeString(auth[1])
		pair := strings.SplitN(string(payload), ":", 2)
		if len(pair) != 2 || !compare(pair[0], pair[1]) {
			response.Write(c, zerrors.WithCode(zcode.ErrSignatureInvalid, "Authorization header format is wrong."), nil)
			c.Abort()
			return
		}

		// 登陆成功设置全局标识
		c.Set(UsernameKey, pair[0])

		c.Next()
	}
}
